import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/extensions.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../model/device_item_model.dart';

class DetailGridWidget extends StatefulWidget {
  final String title;
  final List<DetailItemModel> items;
  final Map? dataSource;
  final bool isLightTtext;

  /// 是否都单独一行展示
  final bool isSingleRow;

  /// 设备基础信息
  final DeviceModel? deviceModel;

  // 第一列占据的宽度 在 0～1之间
  final double firsrtRowPercent;
  const DetailGridWidget(
      {super.key,
      required this.title,
      required this.items,
      this.dataSource,
      this.isSingleRow = false,
      this.isLightTtext = false,
      this.firsrtRowPercent = 0.5,
      this.deviceModel})
      : assert(firsrtRowPercent < 1 && firsrtRowPercent > 0);

  @override
  State<DetailGridWidget> createState() => _DetailGridWidgetState();
}

class _DetailGridWidgetState extends State<DetailGridWidget> {
  double screenWidth = 340.w;
  Map? dataSource;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    dataSource = widget.dataSource;
    // Log.d('widget.dataSource==' + widget.dataSource.toString());
    screenWidth = MediaQuery.of(context).size.width - 32.w;

    return Container(
      color: Colour.white,
      padding: EdgeInsets.only(bottom: 8.h),
      alignment: Alignment.centerLeft,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.title,
            style: TextStyles.f18
                .copyWith(height: 2.8, fontWeight: FontWeight.w500),
          ),
          SizedBox(
            height: 4.h,
          ),
          // Column(children: gridWidget()),
          getGridWrap()
        ],
      ),
    );
  }

  Widget getGridWrap() {
    double col1Width, col2Width;

    if (widget.isSingleRow) {
      col1Width = screenWidth;
      col2Width = screenWidth;
    } else {
      col1Width = screenWidth * widget.firsrtRowPercent;
      col2Width = screenWidth * (1 - widget.firsrtRowPercent);
    }

    return Wrap(
      children: widget.items.mapIndexed((e, i) {
        var value = formateValue(e.field, e.format);
        var width = i % 2 == 0 ? col1Width : col2Width;
        if (isOverflow(context, width, '${e.label}：$value')) {
          width = screenWidth;
        }
        return e.show != null &&
                e.show?.call(value, widget.deviceModel) == false
            ? Gaps.empty
            : cellWidget(e, width);
      }).toList(),
    );
  }

  isOverflow(BuildContext context, double maxWidth, String value) {
    var width = FuncUtils.calculateTextHeight(
        context, value, FontWeight.normal, 14.sp, screenWidth, 1);

    return width >= maxWidth - 2; //2px误差
  }

  Widget cellWidget(DetailItemModel item, double? width) {
    return Container(
      width: width,
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.symmetric(vertical: 5),
      child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(
          '${item.label}：',
          style: item.valueStyles ?? TextStyles.lf14,
        ),
        Text(
          formateValue(item.field, item.format),
          style: widget.isLightTtext
              ? TextStyle(fontSize: 14.sp, color: const Color(0xFFCCCCCC))
              : (item.valueStyles ?? TextStyles.f14),
        ),
      ]),
    );
  }

  String formateValue(String field, Function? formate) {
    Log.d('widget.dataSource==$field  ${widget.dataSource?[field].toString()}');

    if (dataSource == null || dataSource![field] == null) {
      return '--';
    } else if (formate == null) {
      return dataSource![field].toString();
    } else {
      return formate(dataSource![field]).toString();
    }
  }
}
